package com.xu.cloud.common.sequence;

import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * 简单雪花算法
 *
 * @author xuguan
 * @since 2023/12/2
 */
public class SimpleSnowflakeIdSequence implements ISequence {
    // 起始的时间戳，可以根据实际情况设置
    private static final long START_TIMESTAMP = LocalDateTime.of(2000, 1, 1, 0, 0, 0)
            .toInstant(ZoneOffset.of("+8")).toEpochMilli();

    // 每部分占用的位数
    private static final long DATACENTER_BIT = 5; // 数据中心占用的位数
    private static final long MACHINE_BIT = 5;   // 机器标识占用的位数
    private static final long SEQUENCE_BIT = 12; // 序列号占用的位数

    // 每部分的最大值
    private static final long MAX_DATACENTER_ID = -1L ^ (-1L << DATACENTER_BIT);
    private static final long MAX_MACHINE_ID = -1L ^ (-1L << MACHINE_BIT);
    private static final long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT);

    // 每部分向左的位移
    private static final long MACHINE_LEFT = SEQUENCE_BIT;
    private static final long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
    private static final long TIMESTAMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;

    private long lastTimestamp = -1L; // 上一次生成ID的时间戳
    private long datacenterId;      // 数据中心ID
    private long machineId;         // 机器ID
    private long sequence = 0L;     // 序列号

    public SimpleSnowflakeIdSequence(long datacenterId, long machineId) {
        if (datacenterId > MAX_DATACENTER_ID || datacenterId < 0) {
            throw new IllegalArgumentException("Datacenter ID can't be greater than " + MAX_DATACENTER_ID + " or less than 0");
        }
        if (machineId > MAX_MACHINE_ID || machineId < 0) {
            throw new IllegalArgumentException("Machine ID can't be greater than " + MAX_MACHINE_ID + " or less than 0");
        }
        this.datacenterId = datacenterId;
        this.machineId = machineId;
    }

    public synchronized long generateId() {
        long timestamp = System.currentTimeMillis();
        if (timestamp < lastTimestamp) {
            // throw new RuntimeException("Clock moved backwards. Refusing to generate id for " + (lastTimestamp - timestamp) + " milliseconds");
            // 时钟回拨, 使用上一个时间戳生成序列
            timestamp = lastTimestamp;
        }

        if (timestamp == lastTimestamp) {
            // 同一时间戳, 生成的sequence超过最大值会被置0
            sequence = (sequence + 1) & MAX_SEQUENCE;
            if (sequence == 0) {
                // 当前毫秒的序列号用完，等待下一毫秒
                timestamp = waitNextMillis(lastTimestamp);
            }
        }

        if (timestamp > lastTimestamp) {
            // 下一个时间戳重置序列
            sequence = 0L;
        }

        lastTimestamp = timestamp;

        // 生成ID
        return ((timestamp - START_TIMESTAMP) << TIMESTAMP_LEFT)
                | (datacenterId << DATACENTER_LEFT)
                | (machineId << MACHINE_LEFT)
                | sequence;
    }

    private long waitNextMillis(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }

    @Override
    public String nextId() {
        return String.valueOf(this.generateId());
    }
}
